package com.itheima.deepseekaixuhui.Service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.itheima.deepseekaixuhui.Service.DeepSeeKService;
import com.itheima.deepseekaixuhui.pojo.UserInput;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.w3c.dom.Entity;

import static com.itheima.deepseekaixuhui.utils.DeepSeekConstants.AI_DEEPSEEK_KEY;
import static com.itheima.deepseekaixuhui.utils.DeepSeekConstants.BASE_URL;


@Service
public class DeepSeeKServiceImpl implements DeepSeeKService {





    @Override
    public String chatApi(UserInput userInput) {
        //1.获取用户对话信息
        String userInputString = userInput.getUserInputString();
        //2.处理特殊字符
        String replaceString = userInputString.replace("\"", "\\\"");
//        String replaceString = userInput.replace("\"", "\\\"");
        //3.将用户输入信息拼接到请求体
        String requestBody = "{\"model\":\"deepseek-chat\",\"messages\":[{\"role\":\"user\",\"content\":\"" +replaceString+"\"}]}";
        //4.基于httpClients方式新建post请求
        try(CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(BASE_URL);

            //5.设置请求头
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Authorization", "Bearer " + AI_DEEPSEEK_KEY);

            //6.设置请求体
            httpPost.setEntity(new StringEntity(requestBody, "UTF-8"));
            //7.发起请求获取响应信息
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            //8.判断是否为空 不为空则解析响应数据
            if (ObjectUtil.isNotEmpty(entity)) {
                String responseBody = EntityUtils.toString(entity);
                JSONObject jsonObject = JSONUtil.parseObj(responseBody);
                JSONObject choices = jsonObject.getJSONArray("choices").getJSONObject(0);
                String message = choices.getJSONObject("message").toString();
                String[] messageSplit = message.split(":");
                String apiMessage = messageSplit[2].substring(0, messageSplit[2].length() - 2);
                System.out.println(apiMessage);
                return apiMessage;
            }
        } catch (Exception e) {
            System.out.println("请求失败:" + e.getMessage());
        }
        return "请求失败,请稍后再试";
    }
}
